<?php
namespace kernel\library;

class Controller
{
    
    
    /**
     * 设置验证失败后是否抛出异常
     * @access protected
     * @param  bool $fail 是否抛出异常
     * @return $this
     */
    protected function validateFailException($fail = true)
    {
        $this->failException = $fail;
        
        return $this;
    }
    
    /**
     * 验证数据
     * @access protected
     * @param  array        $data     数据
     * @param  string|array $validate 验证器名或者验证规则数组
     * @param  array        $message  提示信息
     * @param  bool         $batch    是否批量验证
     * @param  mixed        $callback 回调方法（闭包）
     * @return array|string|true
     * @throws 
     */
    protected function validate($data, $validate, $message = [], $batch = false, $callback = null)
    {
        if (is_array($validate)) {
            $v = $this->app->validate();
            $v->rule($validate);
        } else {
            if (strpos($validate, '.')) {
                // 支持场景
                list($validate, $scene) = explode('.', $validate);
            }
            $v = $this->app->validate($validate);
            if (!empty($scene)) {
                $v->scene($scene);
            }
        }
        
        // 是否批量验证
        if ($batch || $this->batchValidate) {
            $v->batch(true);
        }
        
        if (is_array($message)) {
            $v->message($message);
        }
        
        if ($callback && is_callable($callback)) {
            call_user_func_array($callback, [$v, &$data]);
        }
        
        if (!$v->check($data)) {
            if ($this->failException) {
                throw new ValidateExcepti($v->getError());
            }
            return $v->getError();
        }
        
        return true;
    }
    
    public function __debugInfo()
    {
        $data = get_object_vars($this);
        unset($data['app'], $data['request']);
        
        return $data;
    }
    
    /**
     * .返回标准的接口数据格式
     * @param array $data
     * @param string $url
     * @return array
     */
    protected function result($data = [], $url = ''){
        $result = [
            'errorcode' => 0,
            'errormsg' => '成功',
            'appenv' => $_SERVER['APP_ENV'],
            'data' => $data,
            'url' => $url,
            'time' => $_SERVER['REQUEST_TIME_FLOAT'],
            'runtime' => microtime(true) - $_SERVER['REQUEST_TIME_FLOAT']
        ];
        Debug::debugInfo($result);
        return $result;
    }
}

